#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import rospy
import sqlite3
import threading
import traceback
import json
import re
class FlaskLog:

    def __init__(self):
        try:
            self._tableName = "flask_log"
            self.__user_database = rospy.get_param('logs_dir', "/home/aoting/user_config/logs/logs_flask.db")
            
            self.__CreateTable()
        except Exception as error:
            # print(error)
             rospy.logerr("[FlaskLog] Failed __init__: {}".format(str(error)))

    def __CreateTable(self):
        '''
            新建表USER
        '''
        needCreate = False
        try:
            connection = sqlite3.connect(self.__user_database)
            cursor = connection.cursor()
            cursor.execute(
                "select name from sqlite_master where type='table' and name = '{}' order by name"
                .format(self._tableName))
            table_data = cursor.fetchall()
            if not table_data:
                needCreate = True
            else:
                cursor.close()
                connection.close()
        except Exception as error:
            rospy.logerr("[FlaskLog] Failed __CreateTable: {}".format(str(error)))
        #  检查表结构

        # 创建表
        if needCreate:
            try:
                cursor.execute("""CREATE TABLE IF NOT EXISTS {} (
                               id INTEGER PRIMARY KEY  AUTOINCREMENT,
							   requsetOrigin TEXT , 
                               requestPath TEXT ,
                               requestBody TEXT, 
                               aotigUser TEXT, 
                               aotigPlatform TEXT,
							   createDate DATETIME DEFAULT (datetime(CURRENT_TIMESTAMP,'localtime'))
                               )""".format(self._tableName, ))
                connection.commit()
                connection.close()
                rospy.loginfo("[FlaskLog] Table created successfully!")
            except Exception as error:
                rospy.logerr("[FlaskLog] Failed to create table: {}".format(
                    str(error)))

    def _insertLog(self, args=None):
        """添加记录
            Keyword arguments:
            argument -- description
            Return: return_description
            """
        try:
            # print("-------_insertLog--------")
            sql_ = """INSERT INTO {} (requsetOrigin,requestPath,requestBody,aotigUser,aotigPlatform) 
                            VALUES ( \'{}\',\'{}\',\'{}\',\'{}\',\'{}\')
                            """.format(
                self._tableName,
                args[0],
                args[1],
                args[2],
                args[3],
                args[4],
            )
            # sql_ = re.sub(r'\s+', ' ', sql_)
            # sql_=sql_.replace('\n', ' ')
            # print(sql_)
            connection = sqlite3.connect(self.__user_database)
            cursor = connection.cursor()
            cursor.execute(sql_)
            connection.commit()
            connection.close()

        except Exception as error:
            print(error)
            rospy.logerr("[FlaskLog] Failed _insertLog: {}".format(str(error)))

    def insertRequestLog(self, request):
        '''
            使用线程添加，避免影响请求的时间
        '''
        print(request)
        # print(request.is_json)
        print(request.headers)
        try:
            if 'X-Real-IP' in request.headers:
                requsetOrigin = request.headers['X-Real-IP']
            elif 'X-Forwarded-For' in request.headers:
                 requsetOrigin = request.headers['X-Forwarded-For'].split(',')[0]
            else:
                requsetOrigin = request.remote_addr
            requestPath = request.headers['HOST']+ request.path
            requsetBody= json.dumps(request.json) if hasattr(request,"json") and request.json else ""  #对象类型
            aotingUser = request.headers.get("Aoting-User") if "Aoting-User" in request.headers else ""  # dict对象
            aotingPlatform = request.headers.get("Aoting-Plaform") if "Aoting-Plaform" in request.headers else ""
            if requsetBody:
                requsetBody = requsetBody.decode('unicode_escape')
            args_ = (requsetOrigin, requestPath, requsetBody, aotingUser,aotingPlatform)
            threading.Thread(target=self._insertLog, args=((args_, ))).start()
        except Exception as error:
            traceback.print_exc()
            rospy.logerr("[FlaskLog] Failed insertRequestLog: {}".format(str(error)))

